package com.tan.mypark.network;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkHttpUtil {
    private static final String TAG = "OkHttpUtil";
    private static OkHttpUtil instance;
    private final OkHttpClient okHttpClient;
    private final Handler handler;

    // 媒体类型常量
    public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
    public static final MediaType FORM = MediaType.get("application/x-www-form-urlencoded; charset=utf-8");

    // 私有构造方法
    private OkHttpUtil() {
        // 构建OkHttpClient实例
        okHttpClient = new OkHttpClient.Builder()
               .connectTimeout(10, TimeUnit.SECONDS)
               .readTimeout(10, TimeUnit.SECONDS)
               .writeTimeout(10, TimeUnit.SECONDS)
               .build();
        
        // 获取主线程的Handler
        handler = new Handler(Looper.getMainLooper());
    }

    // 获取单例实例
    public static OkHttpUtil getInstance() {
        if (instance == null) {
            synchronized (OkHttpUtil.class) {
                if (instance == null) {
                    instance = new OkHttpUtil();
                }
            }
        }
        return instance;
    }

    // 异步GET请求
    public void getAsync(String url, final HttpCallback callback) {
        Request request = new Request.Builder()
               .url(url)
               .build();
        
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "GET请求失败: " + e.getMessage());
                sendFailureCallback(callback, e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String result = response.body().string();
                    Log.d(TAG, "GET请求成功: " + result);
                    sendSuccessCallback(callback, result);
                } else {
                    Log.e(TAG, "GET请求失败: " + response.code());
                    sendFailureCallback(callback, new IOException("HTTP错误码: " + response.code()));
                }
                response.close();
            }
        });
    }

    // 异步POST请求（表单形式）
    public void postAsync(String url, java.util.Map<String, String> params, final HttpCallback callback) {
        FormBody.Builder builder = new FormBody.Builder();
        if (params != null) {
            for (String key : params.keySet()) {
                builder.add(key, params.get(key));
            }
        }
        RequestBody requestBody = builder.build();
        
        Request request = new Request.Builder()
               .url(url)
               .post(requestBody)
               .build();
        
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "POST请求失败: " + e.getMessage());
                sendFailureCallback(callback, e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String result = response.body().string();
                    Log.d(TAG, "POST请求成功: " + result);
                    sendSuccessCallback(callback, result);
                } else {
                    Log.e(TAG, "POST请求失败: " + response.code());
                    sendFailureCallback(callback, new IOException("HTTP错误码: " + response.code()));
                }
                response.close();
            }
        });
    }

    // 异步POST请求（JSON形式）
    public Call postJsonAsync(String url, String json, final HttpCallback callback) {
        RequestBody requestBody = RequestBody.create(json, JSON);
        
        Request request = new Request.Builder()
               .url(url)
               .post(requestBody)
               .build();
        
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "POST JSON请求失败: " + e.getMessage());
                sendFailureCallback(callback, e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String result = response.body().string();
                    Log.d(TAG, "POST JSON请求成功: " + result);
                    sendSuccessCallback(callback, result);
                } else {
                    Log.e(TAG, "POST JSON请求失败: " + response.code());
                    sendFailureCallback(callback, new IOException("HTTP错误码: " + response.code()));
                }
                response.close();
            }
        });
        return null;
    }
//    public void postJsonAsync(String url, String json, final HttpCallback callback) {
//        RequestBody requestBody = RequestBody.create(json, JSON);
//
//        Request request = new Request.Builder()
//                .url(url)
//                .post(requestBody)
//                .build();
//
//        okHttpClient.newCall(request).enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//                Log.e(TAG, "POST JSON请求失败: " + e.getMessage());
//                sendFailureCallback(callback, e);
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                if (response.isSuccessful()) {
//                    String result = response.body().string();
//                    Log.d(TAG, "POST JSON请求成功: " + result);
//                    sendSuccessCallback(callback, result);
//                } else {
//                    Log.e(TAG, "POST JSON请求失败: " + response.code());
//                    sendFailureCallback(callback, new IOException("HTTP错误码: " + response.code()));
//                }
//                response.close();
//            }
//        });
//    }

    // 在主线程回调成功结果
    private void sendSuccessCallback(final HttpCallback callback, final String result) {
        handler.post(() -> {
            if (callback != null) {
                callback.onSuccess(result);
            }
        });
    }

    // 在主线程回调失败结果
    private void sendFailureCallback(final HttpCallback callback, final Exception e) {
        handler.post(() -> {
            if (callback != null) {
                callback.onFailure(e);
            }
        });
    }

    // 回调接口
    public interface HttpCallback {
        void onSuccess(String result);
        void onFailure(Exception e);
    }
}    